import 'package:flutter/material.dart';
import 'package:flutter_hplus/components/tables/index.dart';
import 'package:flutter_hplus/theme/theme.dart';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';

/// 表格内容组件，用于渲染表格主体
class TableContent extends StatefulWidget {
  final List<HDataColumn> columns;
  final List<Map<String, dynamic>> data;
  final List<double> columnWidths;
  final int? hoveredRowIndex;
  final bool showBorder;
  final bool showStripes;
  final bool showHover;
  final Function(int)? onSort;
  final Function(int, double)? onColumnResize;
  final Function(int)? onColumnReset;
  final Function(int?)? onHoverRow;
  final Function(Map<String, dynamic>)? onRowTap;
  final int? sortColumnIndex;
  final bool sortAscending;
  final Function(List<double>)? onColumnWidthsChanged;

  const TableContent({
    super.key,
    required this.columns,
    required this.data,
    required this.columnWidths,
    this.hoveredRowIndex,
    required this.showBorder,
    required this.showStripes,
    required this.showHover,
    this.onSort,
    this.onColumnResize,
    this.onColumnReset,
    this.onHoverRow,
    this.onRowTap,
    this.sortColumnIndex,
    this.sortAscending = true,
    this.onColumnWidthsChanged,
  });

  @override
  State<TableContent> createState() => _TableContentState();
}

class _TableContentState extends State<TableContent> {
  final ScrollController _horizontalScrollController = ScrollController();
  List<double> _calculatedWidths = [];

  @override
  void dispose() {
    _horizontalScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    
    return LayoutBuilder(
      builder: (context, constraints) {
        // 计算总宽度
        final double totalWidth = constraints.maxWidth;
        
        // 计算所有列的总宽度，用于确定是否需要横向滚动
        double columnsTotal = 0.0;
        double totalFlex = 0.0;
        double usedWidth = 0.0;
        List<double> newWidths = List.filled(widget.columns.length, 0.0);
        
        // 第一遍：计算固定宽度和总flex
        for (int i = 0; i < widget.columns.length; i++) {
          final column = widget.columns[i];
          if (widget.columnWidths[i] > 0) {
            usedWidth += widget.columnWidths[i];
            newWidths[i] = widget.columnWidths[i];
          } else if (column.width != null) {
            usedWidth += column.width!;
            newWidths[i] = column.width!;
          } else {
            totalFlex += column.flex;
          }
        }
        
        // 第二遍：分配剩余宽度
        double remainingWidth = totalWidth - usedWidth;
        for (int i = 0; i < widget.columns.length; i++) {
          final column = widget.columns[i];
          if (newWidths[i] == 0) {
            double width = remainingWidth * (column.flex / totalFlex);
            if (column.minWidth != null && width < column.minWidth!) {
              width = column.minWidth!;
            }
            if (column.maxWidth != null && width > column.maxWidth!) {
              width = column.maxWidth!;
            }
            newWidths[i] = width;
          }
          columnsTotal += newWidths[i];
        }
        
        // 如果列宽发生变化，通知父组件
        if (!listEquals(_calculatedWidths, newWidths)) {
          _calculatedWidths = List.from(newWidths);
          if (widget.onColumnWidthsChanged != null) {
            widget.onColumnWidthsChanged!(newWidths);
          }
        }
        
        return Column(
          children: [
            // 表头 - 固定在顶部，水平滚动跟随内容
            SizedBox(
              height: theme.dimens.inputHeight,
              child: SingleChildScrollView(
                controller: _horizontalScrollController,
                scrollDirection: Axis.horizontal,
                child: TableHeader(
                  height: theme.dimens.inputHeight,
                  columns: widget.columns,
                  columnWidths: _calculatedWidths,
                  onSort: widget.onSort ?? (_) {},
                  onColumnResize: widget.onColumnResize ?? (_, __) {},
                  onColumnReset: widget.onColumnReset ?? (_) {},
                  showBorder: widget.showBorder,
                  horizontalScrollController: _horizontalScrollController,
                  sortColumnIndex: widget.sortColumnIndex,
                  sortAscending: widget.sortAscending,
                ),
              ),
            ),
            
            // 表格内容 - 使用 Column 布局
            Expanded(
              child: SingleChildScrollView(
                controller: _horizontalScrollController,
                scrollDirection: Axis.horizontal,
                child: Column(
                  children: [
                    for (int rowIndex = 0; rowIndex < widget.data.length; rowIndex++)
                      MouseRegion(
                        onEnter: (_) {
                          if (widget.showHover && widget.onHoverRow != null) {
                            widget.onHoverRow!(rowIndex);
                          }
                        },
                        onExit: (_) {
                          if (widget.showHover && widget.hoveredRowIndex == rowIndex && widget.onHoverRow != null) {
                            widget.onHoverRow!(null);
                          }
                        },
                        child: HTableRow(
                          rowData: widget.data[rowIndex],
                          columns: widget.columns,
                          columnWidths: _calculatedWidths,
                          rowIndex: rowIndex,
                          isHovered: widget.hoveredRowIndex == rowIndex && widget.showHover,
                          showStripes: widget.showStripes,
                          showBorder: widget.showBorder,
                          onTap: widget.onRowTap != null ? () => widget.onRowTap!(widget.data[rowIndex]) : null,
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ],
        );
      }
    );
  }
} 